module main

import flag { FlagParser }

fn usage(fs FlagParser) string {
	positive_min_arg := (fs.min_free_args > 0)
	positive_max_arg := (fs.max_free_args > 0 && fs.max_free_args != flag.max_args_number)
	no_arguments := (fs.min_free_args == 0 && fs.max_free_args == 0)
	mut adesc := if fs.args_description.len > 0 { fs.args_description } else { '[ARGS]' }
	if no_arguments {
		adesc = ''
	}
	mut use := []string{}
	if fs.application_version != '' {
		use << '$fs.application_name $fs.application_version'
		use << '$flag.underline'
	}
	if fs.application_description != '' {
		use << '$fs.application_description'
		use << ''
	}
	if fs.usage_examples.len == 0 {
		use << 'Usage: $fs.application_name [options] $adesc'
	} else {
		for i, example in fs.usage_examples {
			if i == 0 {
				use << 'Usage: $fs.application_name $example'
			} else {
				use << '   or: $fs.application_name $example'
			}
		}
	}
	use << ''
	// show a message about the [ARGS]:
	if positive_min_arg || positive_max_arg || no_arguments {
		if !no_arguments {
			mut s := []string{}
			if positive_min_arg {
				s << 'at least $fs.min_free_args'
			}
			if positive_max_arg {
				s << 'at most $fs.max_free_args'
			}
			if positive_min_arg && positive_max_arg && fs.min_free_args == fs.max_free_args {
				s = ['exactly $fs.min_free_args']
			}
			sargs := s.join(' and ')
			use << 'The arguments should be $sargs in number.'
			use << ''
		}
	}
	if fs.flags.len > 0 {
		use << 'Options:'
		for f in fs.flags {
			mut onames := []string{}
			if f.abbr != 0 {
				onames << '-$f.abbr.ascii_str(),'
			} else {
				onames << '   '
			}
			if f.name != '' {
				if !f.val_desc.contains('<bool>') {
					onames << '--$f.name $f.val_desc'
				} else {
					onames << '--$f.name'
				}
			}
			option_names := '  ' + onames.join(' ')
			mut xspace := ''
			if option_names.len > flag.space.len - 2 {
				xspace = '\n$flag.space'
			} else {
				xspace = flag.space[option_names.len..]
			}
			fdesc := '$option_names$xspace$f.usage'
			use << fdesc
		}
	}
	for footer in fs.footers {
		use << footer
	}
	return use.join('\n').replace('- ,', '   ')
}
